<template>
	<view class="settle">
		<view class="settle_title">公寓入驻</view>
		<!--  -->
		<view class="info_tab">
			<view class="">
				<view class="lice">
					图片 <text>（请上传房间相关图片）</text>
				</view>
				<view class="lice_image">
					<u-upload :fileList="license_url" @afterRead="files => afterRead(1, files)"
						@delete="files => deletePic(1, files)" multiple :maxCount="6">
					</u-upload>
				</view>
				<view class="access_input">
					<view class="access_input_name">标题</view> <input type="text" v-model="title" placeholder="请输入标题" />
				</view>
				<view class="access_input">
					<view class="access_input_name">区域</view>
					<uni-data-picker style="width: 70%;text-align: left;" placeholder="请选择区域" v-model="city"
						:localdata="cityList" @change="onPickerChange" popup-title="请选择区域"
						:clear-icon="false"></uni-data-picker>
				</view>
				<view class="access_input">
					<view class="access_input_name">详细地址</view> <input type="text" v-model="address"
						placeholder="请输入详细地址" />
				</view>
				<view class="access_input">
					<view class="access_input_name">期望租金</view> <input style="width: 56%;" type="text" v-model="price"
						placeholder="请输入期望租金" />
					<span style="width: 15%;">元/月</span>
				</view>
				<view class="access_input">
					<view class="access_input_name">户型</view> <input type="text" v-model="hourse" placeholder="请输入户型" />
				</view>
				<view class="access_input">
					<view class="access_input_name">面积</view> <input style="width: 56%;" type="text" v-model="area" placeholder="请输入面积" />
					<span style="width: 15%;">㎡</span>
				</view>
				<view class="access_input">
					<view class="access_input_name">楼层</view> <input type="text" v-model="floor" placeholder="请输入楼层" />
				</view>
				<view class="access_input" @click="typeShow=true">
					<view class="access_input_name">类型</view>
					<!-- <input type="text" v-model="type" placeholder="请选择类型" /> -->
					<view class="access_type" :style="type?'color:#333':'color:#ccc'">
						{{type?type:'请选择类型'}}
					</view>
				</view>
				<view class="access_input">
					<!--  @click="show=true" -->
					<view class="access_input_name">电梯</view>
					<!-- <input type="text" v-model="elevator"
						placeholder="请选择是否有电梯" />  :style="elevator?'color:#333':'color:#ccc'"-->
					<view class="access_type">
						<!-- {{elevator?elevator:'请选择是否有电梯'}} -->
						<radio-group @change="radioChange">
							<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in list" :key="item.id"
								style="margin-right: 20rpx;">
								<view>
									<radio backgroundColor="#FF8841" :value="item.id" :checked="item.id === elevator" />
									{{item.name}}
								</view>
							</label>
						</radio-group>
					</view>
				</view>
				<view class="access_input">
					<view class="access_input_name">支付方式</view>
					<view class="access_type">
						<radio-group @change="payRadioChange">
							<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in payList"
								:key="item.name" style="margin-right: 20rpx;">
								<view>
									<radio backgroundColor="#FF8841" :value="item.name"
										:checked="item.name === pay_type" />{{item.name}}
								</view>
							</label>
						</radio-group>
					</view>
					<!-- <input type="text" v-model="pay_type"
						placeholder="请输入支付支付方式" /> -->
				</view>
				<view class="access_input" @click="enterShow=true">
					<view class="access_input_name">入住时间</view>
					<!-- <input type="text" v-model="enter_type"
						placeholder="请选择入住时间" /> -->
					<view class="access_type" :style="enter_type?'color:#333':'color:#ccc'">
						{{enter_type?enter_type:'请选择入住时间'}}
					</view>
				</view>
				<view class="access_input">
					<view class="access_input_name">标签</view> <input type="text" v-model="tags"
						placeholder="如地铁,商超等以逗号分隔" />
				</view>
				<view class="access_input">
					<view class="access_input_name">设施</view>
					<view class="access_type">
						<checkbox-group @change="checkboxChange">
							<label style="margin-right: 20rpx;margin-bottom: 20rpx;" class="uni-list-cell uni-list-cell-pd" v-for="item in ssItems" :key="item.name">
								<view>
									<checkbox :value="item.name" :checked="item.checked" />{{item.name}}
								</view>
							</label>
						</checkbox-group>
					</view>
					<!-- <input type="text" v-model="sheshi"
						placeholder="请输入设施以逗号分隔" /> -->
				</view>
				<view class="access_input">
					<view class="access_input_name">家电</view> 
					<view class="access_type">
						<checkbox-group @change="jdCheckboxChange">
							<label style="margin-right: 20rpx;margin-bottom: 20rpx;" class="uni-list-cell uni-list-cell-pd" v-for="item in jdItems" :key="item.name">
								<view>
									<checkbox :value="item.name" :checked="item.checked" />{{item.name}}
								</view>
							</label>
						</checkbox-group>
					</view>
			<!-- 		<input type="text" v-model="jiadian"
						placeholder="请输入家电以逗号分隔" /> -->
				</view>
				<view class="access_input">
					<view class="access_input_name">其他</view> <input type="text" v-model="qita"
						placeholder="请输入其他以逗号分隔" />
				</view>
			</view>
		</view>
		<view class="settle_title">联系信息</view>
		<view class="info_tab" style="padding-top:0 ;">
			<view class="access_input">
				<view class="access_input_name">称呼</view> <input type="text" v-model="name" placeholder="请输入称呼" />
			</view>
			<view class="access_input">
				<view class="access_input_name">联系方式</view> <input type="text" v-model="phone" placeholder="请输入联系方式" />
			</view>
		</view>
		<!-- 按钮-->
		<view class="button">
			<view class="button_kf" @click="handleLianxi">联系我们</view>
			<view class="button_fd" @click="submit">确认提交</view>
		</view>
		<!-- 		<view class="btn" @click="submit">
			提交
		</view> -->
		<!-- 类型 -->
		<u-action-sheet :actions="typeList" :show="typeShow" @select="typeSelect" @close="typeShow=false"
			cancelText="取消" :safeAreaInsetBottom="true"></u-action-sheet>
		<!-- 是否有电梯 -->
		<u-action-sheet :actions="list" :show="show" @select="elevatorSelect" @close="show=false" cancelText="取消"
			:safeAreaInsetBottom="true"></u-action-sheet>
		<!-- 入住时间 -->
		<u-action-sheet :actions="enterList" :show="enterShow" @select="enterSelect" @close="enterShow=false"
			cancelText="取消" :safeAreaInsetBottom="true"></u-action-sheet>
	</view>
</template>

<script>
	import request from '@/utils/request.js'
	export default {
		data() {
			return {
				ids: '',
				cityList: [],
				dataTree: [], // 初始为空，后续填充
				license_url: [],
				city: "",
				// 
				title: "",
				name: "",
				phone: "",
				price: "",
				type: "",
				hourse: "",
				area: "",
				city_id: "",
				address: "",
				floor: "",
				elevator: "",
				pay_type: "",
				enter_type: "",
				images: [],
				tags: "",
				sheshi: "",
				jiadian: "",
				qita: "",
				// 
				show: false,
				list: [{
						name: '是',
						id: 1
					},
					{
						name: "否",
						id: 2
					}
				],
				payList: [{
						name: '月付'
					},
					{
						name: "季付"
					},
					{
						name: "年付"
					}
				],
				// current: 0,
				//
				enterShow: false,
				enterList: [{
						name: '随时入住',
						id: 1
					},
					{
						name: "预约入住",
						id: 2
					}
				],
				// 
				typeShow: false,
				typeList: [{
						name: '整租',
						id: 1
					},
					{
						name: "合租",
						id: 2
					}
				],
				ssItems: [{
					name: "床 ",
					checked:false
				}, {
					name: "衣柜",
					checked:false
				}, {
					name: "书桌",
					checked:false
				}, {
					name: "沙发",
					checked:false
				}, {
					name: "茶几",
					checked:false
				}, {
					name: "电视柜",
					checked:false
				}, {
					name: "餐桌",
					checked:false
				}, {
					name: "餐椅",
					checked:false
				}, {
					name: "马桶",
					checked:false
				}],
				jdItems:[
					{
						name: "冰箱",
						checked:false
					},
					{
						name: "洗衣机",
						checked:false
					},
					{
						name: "空调",
						checked:false
					},
					{
						name: "热水器",
						checked:false
					},
					{
						name: "抽烟机",
						checked:false
					},
					{
						name: "燃气灶",
						checked:false
					},
					{
						name: "微波炉",
						checked:false
					},
				]

			}
		},
		async onLoad(option) {
			this.transformAddressList()
			this.ids = option.id
			if (option.id) {
				try {
					const response = await request('/v1/rent', 'GET', {
							id: option.id
						},
						'info'); // 只需要传递相对路径
					let data = response.body
					this.title = data.title
					this.name = data.name
					this.phone = data.phone
					this.price = data.price
					this.type = data.type == 1 ? '整租' : '合租'
					this.hourse = data.house
					this.area = data.area
					this.city = data.city_id
					this.city_id = data.city_id
					this.address = data.address
					this.floor = data.floor
					this.elevator = data.elevator
					this.pay_type = data.pay_type
					this.enter_type = data.enter_type == 1 ? '随时入住' : '预约入住'
					// this.images=[]
					this.license_url = data.images.map(image => ({
						url: image
					}))
					this.tags = data.tags.join(',')
					this.sheshi = data.info.设施
					this.ssItems.forEach(item => {
					  if (this.sheshi.includes(item.name)) {
					    item.checked = true;
					  }
					});
					this.jiadian = data.info.家电
					this.jdItems.forEach(item => {
					  if (this.jiadian.includes(item.name)) {
					    item.checked = true;
					  }
					});
					this.qita = data.info.其他.join(',')
				} catch (error) {
					console.error('请求失败:', error);
				}
			}
		},
		mounted() {

		},
		methods: {
			transformData(data) {
				return data.map(item => ({
					text: item.name, // 将 name 改为 text
					value: item.id, // 将 id 改为 value
					children: item.child ? this.transformData(item.child) : [] // 将 child 改为 children
				}));
			},
			async transformAddressList() {
				try {
					const response = await request('/v1/city', 'GET', {}, 'tree');
					if (response) {
						this.cityList = this.transformData(response.body);
					}

				} catch (error) {
					console.error('请求失败:', error);
				}
			},
			//电梯
			elevatorSelect(e) {
				// console.log(e);
				// this.elevator = e.name
			},
			radioChange: function(evt) {
				// console.log(evt);
				for (let i = 0; i < this.list.length; i++) {
					if (this.list[i].id === evt.detail.value) {
						this.elevator = this.list[i].id;
						break;
					}
				}
				// console.log(this.elevator ,11);
			},
			//支付方式
			payRadioChange: function(evt) {
				// console.log(evt);
				for (let i = 0; i < this.payList.length; i++) {
					if (this.payList[i].name === evt.detail.value) {
						this.pay_type = this.payList[i].name;
						break;
					}
				}
				// console.log(this.pay_type, 11);
			},
			//入住
			enterSelect(e) {
				this.enter_type = e.name
			},
			//类型
			typeSelect(e) {
				this.type = e.name
			},
			//设施
			checkboxChange: function(e) {
				var items = this.ssItems,
					values = e.detail.value;
				for (var i = 0, lenI = items.length; i < lenI; ++i) {
					const item = items[i]
					if (values.includes(item.name)) {
						this.$set(item, 'checked', true)
					} else {
						this.$set(item, 'checked', false)
					}

				}
				// console.log(items);
				this.sheshi=items.filter(item => item.checked).map(item => item.name)
				// console.log(this.sheshi);
			},
			//家电
			jdCheckboxChange: function(e) {
				var items = this.jdItems,
					values = e.detail.value;
				for (var i = 0, lenI = items.length; i < lenI; ++i) {
					const item = items[i]
					if (values.includes(item.name)) {
						this.$set(item, 'checked', true)
					} else {
						this.$set(item, 'checked', false)
					}

				}
				// console.log(items);
				this.jiadian=items.filter(item => item.checked).map(item => item.name)
				// console.log(this.sheshi);
			},
			// 地区
			async onPickerChange(selectedValue) {
				// console.log(selectedValue,666);
				// this.value=selectedValue[selectedValue.length - 1].text
				this.city_id = selectedValue.detail.value[selectedValue.detail.value.length - 1].value
				// console.log(this.city_id);
			},
			afterRead(index, file) {
				const maxSize = 5 * 1024 * 1024; // 2MB
				if (file.file[0].size > maxSize) {
					uni.showToast({
						title: '文件大小不能超过 5MB',
						icon: 'none'
					})
					return;
				}
				this.upLoad(index, file)
			},
			deletePic(index, file) {
				console.log(index, file)
				const indexs = file.index
				if (index == 1) {
					this.license_url = this.license_url.filter((_, i) => i !== indexs)
				}
			},
			async upLoad(index, event) {
				const {
					file
				} = event;
				const fileName = file[0].url.substring(file[0].url.lastIndexOf('/') + 1)
				const res = await request('/v1/oss', 'GET', {
					file: fileName
				}, 'sts');
				this.hostUrl = res.body
				const formData = {
					key: `${res.body.dir.replace(/^\/+/, '')}`,
					OSSAccessKeyId: res.body.accessid,
					policy: res.body.policy,
					signature: res.body.signature,
					success_action_status: 200,
					keys: res.body.path,
				};
				let that = this
				uni.uploadFile({
					url: res.body.host, // 替换为你的服务器地址
					filePath: file[0].url,
					name: 'file',
					formData: formData,
					success: (res) => {
						const uploadedFileUrl = that.hostUrl.host + '/' + formData.key
						// console.log(uploadedFileUrl);
						if (index == 1) {
							that.license_url.push({
								url: uploadedFileUrl
							});

							// 将每个 URL 推入 license_url 数组
							// uploadedFileUrls.forEach(url => {
							//   that.license_url.push({ url });
							// });
							console.log(that.license_url);
						}
					},
					fail: (err) => {
						console.log('上传失败', err);
					}
				})
			},
			//ocr
			// async ossOcr(index) {
			// 	if (index == 1) {
			// 		const res = await request('/v1/ocr', 'POST', {
			// 			type: 'license',
			// 			url: this.license_url.map(item => item.url)[0]
			// 		});
			// 		if (res) {
			// 			console.log(res);
			// 			const data = res.body
			// 			this.license = {
			// 				name: data.name,
			// 				register_number: data.reg_num, //执照号
			// 				license_type: data.valid_period == '29991231' ? 0 : 1, //有效期类型
			// 				establish_date: this.convertDateFormat(data.establish_date), //注册日期
			// 				valid_period: this.convertDateFormat(data.valid_period),
			// 				address: data.address, //注册地址
			// 				license_image_url: this.license_url.map(item => item.url)[0]
			// 			}
			// 			this.license_type_name = data.valid_period == '29991231' ? '长期' : '短期'
			// 		}
			// 	}

			// },
			onShowToast(name) {
				uni.showToast({
					title: name + '不能为空',
					icon: 'none'
				})
			},
			handleLianxi() {
				uni.showModal({
					title: '联系我们',
					content: '18687405643',
					cancelColor: '#000000',
					confirmColor: '#FF8841',
					success: function(res) {
						if (res.confirm) {
							uni.makePhoneCall({
								phoneNumber: '18687405643',
							});
						} else if (res.cancel) {

						}
					}
				});
			},
			async submit() {
				console.log(this.elevator);
				if (this.license_url.length == 0) return this.onShowToast("房间图片不能为空")
				if (!this.title) return this.onShowToast("标题不能为空")
				if (!this.city_id) return this.onShowToast("区域不能为空")
				if (!this.address) return this.onShowToast("详细地址不能为空")
				if (!this.price) return this.onShowToast("租金不能为空")
				if (!this.hourse) return this.onShowToast("户型不能为空")
				if (!this.area) return this.onShowToast("面积不能为空")
				if (!this.floor) return this.onShowToast("楼层不能为空")
				if (!this.type) return this.onShowToast("类型不能为空")
				if (!this.elevator) return this.onShowToast("是否有电梯不能为空")
				if (!this.pay_type) return this.onShowToast("支付方式不能为空")
				if (!this.enter_type) return this.onShowToast("入住时间不能为空")
				if (!this.name) return this.onShowToast("称呼不能为空")
				if (!this.phone) return this.onShowToast("联系方式不能为空")
				try {
					let params = {
						title: this.title,
						name: this.name,
						phone: this.phone,
						price: this.price,
						type: this.type == '整租' ? 1 : 2,
						house: this.hourse,
						area: this.area,
						city_id: this.city_id,
						address: this.address,
						floor: this.floor,
						elevator: this.elevator,
						pay_type: this.pay_type,
						enter_type: this.enter_type == '随时入住' ? 1 : 2,
						images: this.license_url.map(item => item.url),
						tags: this.tags.split(/[,，]/),
						info: {
							"设施": this.sheshi,
							"家电": this.jiadian,
							"其他": this.qita.split(/[,，]/)
						},
						id: this.ids
					}
					// console.log);
					// return
					const response = await request('/v1/rent', this.ids ? 'PUT' : 'POST', params,
						this.ids ? 'update' : 'add'); // 只需要传递相对路径
					uni.showToast({
						title: "成功",
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/index/index'
						})
					}, 1000)
				} catch (error) {
					console.error('请求失败:', error);
				}
			}
		}
	}
</script>

<style>
	.settle {
		/* padding: 0 36rpx; */
		background: #f4f4f4;
		min-height: 100vh;
		/* padding-bottom: 40rpx; */
		box-sizing: border-box;
	}

	.settle_title {
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		font-size: 36rpx;
		color: #333333;
		padding: 32rpx 36rpx;
		/* margin-bottom: ; */
	}

	.info_tab {
		width: 90%;
		margin: 0 auto;
		background-color: #fff;
		padding: 32rpx;
		box-sizing: border-box;
		border-radius: 16rpx;

	}

	.lice {
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #333333;
		line-height: 40rpx;
		text-align: left;
		font-style: normal;
		/* margin-top: 32rpx; */
	}

	.lice text {
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 24rpx;
		color: #999999;
		line-height: 34rpx;
		text-align: left;
		font-style: normal;
	}

	.lice_image {
		/* width: 100%; */
		margin: 0 auto;
		margin-top: 30rpx;
	}

	.access_input {
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-bottom: 1px solid #F6F6F6;
		padding: 24rpx 0;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #333333;
		line-height: 40rpx;
		text-align: left;
		font-style: normal;
	}

	.access_input .access_input_name {
		width: 29%;
	}

	.access_input input {
		width: 70%;
		text-align: left;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		line-height: 40rpx;
		font-style: normal;

	}

	.btn {
		width: 95%;
		height: 88rpx;
		margin: 0 auto;
		background: linear-gradient(137deg, #26D180 0%, #00AA47 100%);
		border-radius: 44rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		font-size: 32rpx;
		color: #FFFFFF;
		line-height: 88rpx;
		text-align: center;
		font-style: normal;
		margin-top: 68rpx;
		margin-bottom: 24rpx;
	}

	.input-value-border {
		width: 100% !important;
		border: none !important;
	}

	.selected-area {
		color: #ccc !important;
	}

	.uni-data-pickerview>.selected-area {
		color: #333 !important;
	}

	.button {
		width: 100%;
		background: #fff;
		margin-top: 80rpx;
		display: flex;
		justify-content: space-between;
		padding: 0 36rpx;
		padding-bottom: 50rpx;
		padding-top: 20rpx;
		box-sizing: border-box;
	}

	.button_kf {
		width: 30%;
		height: 88rpx;
		border-radius: 16rpx;
		border: 2rpx solid #FF7623;
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		font-size: 32rpx;
		color: #FF7623;
		line-height: 88rpx;
		text-align: center;
	}

	.button_fd {
		width: 65%;
		height: 88rpx;
		background: linear-gradient(314deg, #FF6F55 0%, #FF8841 100%);
		border-radius: 16rpx;
		text-align: center;
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		font-size: 32rpx;
		color: #FFFFFF;
		line-height: 88rpx;
	}

	.access_type {
		width: 69%;
		text-align: left;
	}
</style>